#include "Loaders/TextureLoader.h"
#include "Core/ResourceManager.h"
#include "Debug/Exceptions.h"
#include "SOIL.h"

namespace blue {

TextureLoader::TextureLoader()
{
}

TextureLoader::~TextureLoader()
{
}

Texture *TextureLoader::loadFromFile(const char *filename)
{
    ResourceManager *rsmgr = ResourceManager::instance();
    Texture *texture = rsmgr->get<Texture>(filename);
    if(!texture)
    {
        Vector2i size;
        int channels;
        unsigned char *data = SOIL_load_image
        (
            filename,
            &size.X, &size.Y, &channels,
            SOIL_LOAD_AUTO
        );

        GLuint texID = SOIL_create_OGL_texture
        (
            data,
            size.X, size.Y, channels,
            SOIL_CREATE_NEW_ID,
            SOIL_FLAG_MIPMAPS | SOIL_FLAG_INVERT_Y | SOIL_FLAG_NTSC_SAFE_RGB | SOIL_FLAG_COMPRESS_TO_DXT
        );

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

        if(!data || !glIsTexture(texID))
            throw LoadingFailed(filename, "Couldn't load texture.");

        texture = new Texture(texID, size, channels, data, filename);
        rsmgr->add(texture);
    }
	return texture;
}

}
